package com.qzsoft.zhjd.materiel.modules.materielproject.service.impl;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qzsoft.zhjd.common.annotation.ZhjdDataFilter;
import com.qzsoft.zhjd.common.components.BaseServiceComponent;
import com.qzsoft.zhjd.common.enums.BizCode;
import com.qzsoft.zhjd.common.utils.RenExceptionUtils;
import com.qzsoft.zhjd.materiel.modules.materielproject.dto.MaterielProjectListDto;
import com.qzsoft.zhjd.materiel.modules.materielproject.entity.MaterielProjectEntity;
import com.qzsoft.zhjd.materiel.modules.materielproject.entity.MaterielProjectItemEntity;
import com.qzsoft.zhjd.materiel.modules.materielproject.mapper.MaterielProjectMapper;
import com.qzsoft.zhjd.materiel.modules.materielproject.service.MaterielProjectService;
import com.qzsoft.zhjd.materiel.modules.materielproject.service.MaterielProjectItemService;

/**
 * @ClassName MaterielProjectServiceImpl
 * @Description 项目材料业务接口实现
 * @author linhuawei
 * @since 2022-03-30
 */
@Service
public class MaterielProjectServiceImpl extends ServiceImpl<MaterielProjectMapper, MaterielProjectEntity>
        implements MaterielProjectService {

    @Autowired
    private BaseServiceComponent baseServiceComponent;

    @Autowired
    private MaterielProjectItemService materielProjectItem1Service;


//    @Autowired
//    private MaterielApiVesionService materielApiVesionService;
//
//    @Autowired
//    private MaterielProjectService materielProjectService;
//
//    @Autowired
//    private ZhjdSysDeptService zhjdSysDeptService;
//
//    @Autowired
//    private MaterielApiService materielApiService;
//
//    @Value("${zhjd.upload.getMaterialAcceptor}")
//    private String getMaterialAcceptor;

    @Override
    @ZhjdDataFilter(tableAlias = "t1")
    public IPage<MaterielProjectListDto> page(Map<String, Object> params) {
        IPage<MaterielProjectListDto> page = baseServiceComponent.getPage(params, MaterielProjectListDto.class);
        return baseMapper.queryDto(page, params);
    }

    @Override
    @ZhjdDataFilter
    public List<MaterielProjectEntity> list(Map<String, Object> params) {
        QueryWrapper<MaterielProjectEntity> queryWrapper = new QueryWrapper<MaterielProjectEntity>();
        if (ObjectUtils.isNotEmpty(params.get("baseCode"))) {
            queryWrapper.eq("base_code", params.get("baseCode").toString());
        }
        if (ObjectUtils.isNotEmpty(params.get(ZhjdDataFilter.DATA_FILTER_SQL))) {
            queryWrapper.apply(params.get(ZhjdDataFilter.DATA_FILTER_SQL).toString());
        }
        queryWrapper.orderByAsc("base_code, name");
        return baseMapper.selectList(queryWrapper);
    }

    @Override
    public List<MaterielProjectEntity> getByBaseCode(String baseCode) {
        QueryWrapper<MaterielProjectEntity> queryWrapper = new QueryWrapper<MaterielProjectEntity>();
        queryWrapper.eq("base_code", baseCode);
        queryWrapper.orderByAsc("base_code, name");
        return baseMapper.selectList(queryWrapper);
    }

    @Override
    public MaterielProjectEntity getByIdWithItemList(String id) {
        MaterielProjectEntity entity = baseMapper.selectById(id);
        if (null != entity) {
            List<MaterielProjectItemEntity> itemList = materielProjectItem1Service.listByProjectId(id);
            if (null == itemList) {
                itemList = new ArrayList<MaterielProjectItemEntity>();
            }
            entity.setItemList(itemList);
        }
        return entity;
    }

//    @Override
//    @Transactional(rollbackFor = Exception.class)
//    public void getUrlInfo() throws IOException {
//        //获取访问接口的url
//        String url = getMaterialAcceptor;
//        Map<String,Object> params = new HashMap<String,Object>();
//        Long getProjectList = materielApiVesionService.getVersionByCode("getProjectList");
//        params.put("getProjectList",String.valueOf(getProjectList));
//        //获取第三方名称的编码
//        Map<String,String> dicts = getNickNameByCode();
//        //发送请求
//        String result = HttpUtil.get(url,params);
//        JSONObject resultJson = JSONObject.parseObject(result);
//        if(resultJson == null){
//            RenExceptionUtils.throwEx(BizCode.EXCEPTION, "传输数据格式不正确");
//        }
//        Integer status = resultJson.getInteger("code");
//        if(status != 200){
//            RenExceptionUtils.throwEx(BizCode.EXCEPTION, "请求失败");
//        }
//        JSONArray datas = resultJson.getJSONArray("data");
//        if(datas == null){
//            RenExceptionUtils.throwEx(BizCode.EXCEPTION, "返回数据格式异常");
//        }
//        //获取响应收料单位数据
//        List<RequestProjectDto> acceptors =  datas.toJavaList(RequestProjectDto.class);
//        //更新version
//        materielApiVesionService.updateByCode("getProjectList");
//        //删除表中数据
//        materielProjectService.remove(null);
//        //存入收料单位数据
//        for(RequestProjectDto acceptor : acceptors){
//            MaterielProjectEntity materielProjectEntity = new MaterielProjectEntity();
//            materielProjectEntity.setName(acceptor.getName());
//            materielProjectEntity.setEnable(acceptor.getEnable());
//            String code = dicts.get(acceptor.getSiteCode());
//            materielProjectEntity.setBaseCode(code);
//            materielProjectService.save(materielProjectEntity);
//        }
//    }

    @Override
    public boolean save(MaterielProjectEntity entity) {
        // 判断项目名称
        checkName(entity);
        // 保存项目信息
        super.save(entity);
        // 保存项目材料信息
        List<MaterielProjectItemEntity> itemList = entity.getItemList();
        if (ObjectUtils.isNotEmpty(itemList)) {
            String projectId = entity.getId();
            for (MaterielProjectItemEntity itemEntity : itemList) {
                itemEntity.setId(null);
                itemEntity.setProjectId(projectId);
            }
            materielProjectItem1Service.saveBatch(itemList);
        }

        // 返回结果
        return true;
    }

//    private  Map<String,String> getNickNameByCode(){
//        List<ZhjdSysDeptEntity>  depts = zhjdSysDeptService.list();
//        Map<String, String> params = new HashMap<String, String>();
//        for(ZhjdSysDeptEntity dept : depts) {
//            if(dept.getCode() != null && dept.getNickCode() != null) {
//                params.put(dept.getNickCode(), dept.getCode());
//            }
//            }
//        return params;
//    }

    @Override
    public boolean updateById(MaterielProjectEntity entity) {
        // 判断项目名称
        checkName(entity);

        // 更新项目信息
        super.updateById(entity);

        // 删除材料信息
        String projectId = entity.getId();
        materielProjectItem1Service.deleteByProjectId(projectId);

        // 保存项目材料信息
        List<MaterielProjectItemEntity> itemList = entity.getItemList();
        if (ObjectUtils.isNotEmpty(itemList)) {
            for (MaterielProjectItemEntity itemEntity : itemList) {
                itemEntity.setId(null);
                itemEntity.setProjectId(projectId);
            }
            materielProjectItem1Service.saveBatch(itemList);
        }

        // 返回结果
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeById(Serializable id) {
        // TODO 判断是否可以删除

        // 删除材料信息
        materielProjectItem1Service.deleteByProjectId(id);

        // 删除项目信息
        return super.removeById(id);
    }

    /**
     * @Title checkName
     * @Description 校验项目名称
     * @param entity
     */
    private void checkName(MaterielProjectEntity entity) {
        QueryWrapper<MaterielProjectEntity> queryWrapper = new QueryWrapper<MaterielProjectEntity>();
        queryWrapper.eq("base_code", entity.getBaseCode());
        queryWrapper.eq("name", entity.getName());
        if (ObjectUtils.isNotEmpty(entity.getId())) {
            queryWrapper.ne("id", entity.getId());
        }
        Integer count = baseMapper.selectCount(queryWrapper);
        if (null != count && 0 < count) {
            RenExceptionUtils.throwEx(BizCode.PARAMS_ERROR, "单位/项目[" + entity.getName() + "]已经存在");
        }
    }

}
